import numpy as np
import pyqtgraph as pg
import sys
# from rob import Rob
from mechanism import Mechanism

app = pg.mkQApp()  # 建立app
win = pg.GraphicsWindow()  # 建立窗口
win.setWindowTitle(u'机械原理杆组运动仿真')
win.resize(1200, 700)  # 小窗口大小
# 创建图表
p = win.addPlot()  # 把图p加入到窗口中
p.showGrid(x=True, y=True)  # 把X和Y的表格打开
p.setRange(xRange=[-1.2, 1], yRange=[-0.7, 0.7], padding=0) 
  

mechanisms = [] # 机构
cuvers = [] # 画笔

def add_mechanism(m:Mechanism):
  """
  添加一个待绘制的杆组
  """
  mechanisms.append(m)

  global p # 添加画笔
  for r in m.get_robs():cuvers.append(p.plot())
  


def start_draw(starttime,holdtime,interval_ms):
  global time_after_draw,interval,hold_time,timer
  time_after_draw = starttime
  interval = interval_ms
  hold_time = holdtime+starttime

  timer = pg.QtCore.QTimer()
  timer.timeout.connect(flush)#定时调用_flush函数
  timer.start(max(interval_ms,20))#多少ms调用一次

  sys.exit(app.exec_())


def flush():
  global time_after_draw,interval,hold_time,timer
  time_after_draw +=interval
  if(time_after_draw> hold_time):timer.stop()

  t_s = time_after_draw/1000
  for m in mechanisms:
    m.update(t_s)
    for r in m.get_robs():
      cuvers[r.index].setData((r.basePoint.x,r.endPoint.x),(r.basePoint.y,r.endPoint.y))
    

if __name__ == '__main__':
  pass
  